package com.kawins.mina.net;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.filter.codec.demux.MessageEncoder;

import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Map;

public class HttpResponseEncoder implements MessageEncoder<HttpResponseMessage> {
	private static final byte[] CRLF = { 13, 10 };

	@Override
	public void encode(IoSession session, HttpResponseMessage msg, ProtocolEncoderOutput out) throws Exception {
		IoBuffer buf = IoBuffer.allocate(256);

		buf.setAutoExpand(true);
		try {
			CharsetEncoder encoder = Charset.defaultCharset().newEncoder();
			buf.putString("HTTP/1.1 ", encoder);
			buf.putString(String.valueOf(msg.getResponseCode()), encoder);
			switch (msg.getResponseCode()) {
			case 200:
				buf.putString(" OK", encoder);
				break;
			case 404:
				buf.putString(" Not Found", encoder);
			}

			buf.put(CRLF);
			for (Map.Entry<String, String> entry : msg.getHeaders().entrySet()) {
				buf.putString((CharSequence) entry.getKey(), encoder);
				buf.putString(": ", encoder);
				buf.putString((CharSequence) entry.getValue(), encoder);
				buf.put(CRLF);
			}

			buf.putString("Content-Length: ", encoder);
			buf.putString(String.valueOf(msg.getBodyLength()), encoder);
			buf.put(CRLF);
			buf.put(CRLF);

			buf.put(msg.getBody());
		} catch (CharacterCodingException ex) {
			ex.printStackTrace();
		}

		buf.flip();
		out.write(buf);
	}

}
